package com.dingding.order.core.pay.biz.impl;

import javax.annotation.Resource;

import org.apache.http.HttpStatus;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.base.dto.AbstractResponse;
import com.dingding.common.core.base.dto.ResponseEntity;
import com.dingding.common.core.beans.UserTaxiOrdert;
import com.dingding.common.core.beans.Userorder;
import com.dingding.common.core.beans.Userordert;
import com.dingding.common.core.beans.special.Userspecialorder;
import com.dingding.common.core.beans.special.UserspecialorderT;
import com.dingding.common.core.util.MD5Util;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.common.core.util.tools.wechat.pay.WechatPayApi;
import com.dingding.common.core.util.tools.wechat.pay.paybean.WechatPayOrderQueryResponse;
import com.dingding.common.core.util.tools.wechat.pay.paybean.request.WechatPayOrderQueryRequest;
import com.dingding.order.code.GrabOrderCodeMsg;
import com.dingding.order.code.order.OrderStatus;
import com.dingding.order.code.order.SpecialOrderStatus;
import com.dingding.order.code.order.TaxiOrderStatus;
import com.dingding.order.core.pay.biz.IGetPayResultService;
import com.dingding.order.core.pay.biz.IPayNotifyService;
import com.dingding.order.core.pay.dao.IOrderPayDao;
import com.dingding.order.core.pay.dao.IPayUserOrderDao;
import com.dingding.order.core.pay.dao.ITaxiOrderPayDao;
import com.dingding.order.core.special.dao.ISpecialOrderDao;
import com.dingding.order.core.special.dao.ISpecialOrderFormalDao;
import com.dingding.order.dto.pay.GetPayResultCodeMsg;
import com.dingding.order.dto.pay.ReqTaxiQueryOrderResultDTO;
import com.dingding.order.dto.pay.ResTaxiQueryOrderResultDTO;
import com.dingding.order.dto.pay.menums.TransactionTypeEnum;

/**
 * 
 * @ClassName: GetPayResultServiceImpl 
 * @Description: 获取支付结果业务实现类
 * @author YHQ
 * @date 2016年7月7日 上午11:20:46
 * @version V2.3.0
 */
@Component("getPayResultService")
public class GetPayResultServiceImpl extends AbstractResponse<ResTaxiQueryOrderResultDTO, ReqTaxiQueryOrderResultDTO>
		implements IGetPayResultService {

	private Logger log = Logger.getLogger(this.getClass());

	@Resource(name = "taxiOrderPayDao")
	private ITaxiOrderPayDao taxiOrderPayDao;

	@Resource(name = "payUserOrderDao")
	private IPayUserOrderDao payUserOrderDao;

	@Resource(name = "payNotifyService")
	private IPayNotifyService payNotifyService;

	@Resource(name = "orderPayDao")
	private IOrderPayDao orderPayDao;
	
	@Resource(name = "specialOrderFormalDao")
	private ISpecialOrderFormalDao specialOrderFormalDao;
	
	@Resource(name = "specialOrderDao")
	private ISpecialOrderDao specialOrderDao;

	/**
	 * 
	 * @Title: getPayResult 
	 * @Description: 获取支付结果
	 * @param requestJson 客户端请求JSON
	 * @author YHQ 
	 * @return String    返回类型
	 * 
	 */
	@Override
	public String getPayResult(String requestJson) {

		// 解析客户端请求的JSON数据
		ReqTaxiQueryOrderResultDTO reqTaxiQueryOrderResultDTO = super.parseRequestJson(requestJson);
		ResponseEntity<ResTaxiQueryOrderResultDTO> response = new ResponseEntity<ResTaxiQueryOrderResultDTO>();

		// 判断客户端请求参数是否为空
		if (!super.validateParam(response, reqTaxiQueryOrderResultDTO)) {
			return super.responseBeanToJson(response);
		}

		// 正式表获取该订单
		Userorder userOrder = this.getOrderInfo(reqTaxiQueryOrderResultDTO.getOid(), response);
		
		//专车的正式表
		Userspecialorder userspecialorder = this.specialOrderFormalDao.getById(reqTaxiQueryOrderResultDTO.getOid());

		if (reqTaxiQueryOrderResultDTO.getRegistrationType() == 1) { // 私家车

			Userordert userordert = this.getOrdertInfo(reqTaxiQueryOrderResultDTO.getOid(), response);

			// 正式表中有该订单，并且状态为已完成
			getPayResultCondition(userOrder, userordert, response);

		} else if (reqTaxiQueryOrderResultDTO.getRegistrationType() == 2) { // 出租车

			// 出租车临时表获取该订单
			UserTaxiOrdert taxiOrdert = this.getTaxiOrdert(reqTaxiQueryOrderResultDTO.getOid(), response);

			// 正式表中有该订单，并且状态为已完成
			getPayResultCondition(userOrder, taxiOrdert, response);
		
		} else if(reqTaxiQueryOrderResultDTO.getRegistrationType() == 3){//专车
			
			//获取专车临时订单表
			UserspecialorderT userspecialordert = this.specialOrderDao.getById(reqTaxiQueryOrderResultDTO.getOid());
		
			// 正式表中有该订单，并且状态为已完成
			getPayResultCondition(userspecialorder , userspecialordert, response);
			
		}

		return super.responseBeanToJson(response);
	}


	/**
	 * @Description:获取专车订单支付结果
	 * @author fengshuonan
	 * @since 2.4
	 */
	private void getPayResultCondition(Userspecialorder userspecialorder, UserspecialorderT userspecialordert,
			ResponseEntity<ResTaxiQueryOrderResultDTO> response) {
		ResTaxiQueryOrderResultDTO queryOrderResult = new ResTaxiQueryOrderResultDTO();
		
		// 正式表存在该订单，并且状态为已完成
		if (userspecialorder != null && userspecialorder.getOrderStatus() == SpecialOrderStatus.ORDER_OK) {

			// 1：支付成功 2：支付失败
			queryOrderResult.setOrderStatus(1);
			response.setCode(HttpStatus.SC_OK);
			response.setErrorMessage(GetPayResultCodeMsg.GET_PAY_RESULT_SUCCESS);
			response.setPromptMessage(GetPayResultCodeMsg.GET_PAY_RESULT_SUCCESS);
			response.setResponseBody(queryOrderResult);
			return;
		}

		// 临时订单不为空，并且状态为已完成
		if (userspecialordert != null && userspecialordert.getOrderStatus() == SpecialOrderStatus.ORDER_OK) {

			// 1：支付成功 2：支付失败
			queryOrderResult.setOrderStatus(1);

			response.setCode(HttpStatus.SC_OK);
			response.setErrorMessage(GetPayResultCodeMsg.GET_PAY_RESULT_SUCCESS);
			response.setPromptMessage(GetPayResultCodeMsg.GET_PAY_RESULT_SUCCESS);
			response.setResponseBody(queryOrderResult);
			return;
			
		// 临时订单不为空，并且状态为待支付
		}else if(userspecialordert != null && userspecialordert.getOrderStatus() == SpecialOrderStatus.ORDER_WARIT_PAY){  
			
			if (wechatPayIsOk(userspecialordert.getSpecialOrderId())) {

				userspecialordert.setOrderStatus(SpecialOrderStatus.ORDER_OK);
				
				// 改变订单状态为已支付
				this.specialOrderDao.update(userspecialordert);
				
				// 1：支付成功 2：支付失败
				queryOrderResult.setOrderStatus(1);
				response.setCode(HttpStatus.SC_OK);
				response.setErrorMessage(GetPayResultCodeMsg.GET_PAY_RESULT_SUCCESS);
				response.setPromptMessage(GetPayResultCodeMsg.GET_PAY_RESULT_SUCCESS);
				response.setResponseBody(queryOrderResult);
				return;
			}
			
		}

		// 1：支付成功 2：支付失败
		queryOrderResult.setOrderStatus(2);

		response.setCode(HttpStatus.SC_FORBIDDEN);
		response.setErrorMessage(GetPayResultCodeMsg.GET_PAY_RESULT_ERROR);
		response.setPromptMessage(GetPayResultCodeMsg.GET_PAY_RESULT_ERROR);
		response.setResponseBody(queryOrderResult);

		return;
	}

	/**
	 * 
	 * @Title: geTaxiOrdert 
	 * @Description: 根据出租车订单Id获取订单信息 
	 * @param oid 订单Id
	 * @author YHQ 
	 * @return UserTaxiOrdert    返回类型
	 * @version V2.3.0
	 * 
	 */
	@Transactional(readOnly = true)
	public UserTaxiOrdert getTaxiOrdert(String oid, ResponseEntity<ResTaxiQueryOrderResultDTO> response) {

		// 创建用于存储出租车订单的对象
		UserTaxiOrdert taxiOrdert = null;

		try {
			taxiOrdert = taxiOrderPayDao.getById(oid);
		} catch (Exception e) {

			response.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
			response.setErrorMessage(GrabOrderCodeMsg.GET_TAXI_ORDER_INFO_ERROR);
			response.setPromptMessage(GrabOrderCodeMsg.GET_TAXI_ORDER_INFO_ERROR_CLIENT);
			log.error("根据出租车订单Id获取订单信息时出现异常   类：" + this.getClass() + " geTaxiOrdert()", e);
			return taxiOrdert;
		}

		// 如果订单不存在，则给出相应的错误信息
		if (taxiOrdert == null) {
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(GrabOrderCodeMsg.ORDER_NOT_EXISTS);
			response.setPromptMessage(GrabOrderCodeMsg.ORDER_NOT_EXISTS);
		}

		return taxiOrdert;
	}

	/**
	 * 
	 * @Title: getOrdertInfo 
	 * @Description: 根据出租车订单Id获取订单信息 
	 * @param oid 订单Id
	 * @author YHQ 
	 * @return UserTaxiOrdert    返回类型
	 * @version V2.3.0
	 * 
	 */
	@Transactional(readOnly = true)
	public Userordert getOrdertInfo(String oid, ResponseEntity<ResTaxiQueryOrderResultDTO> response) {

		// 创建用于存储出租车订单的对象
		Userordert userOrdert = null;

		try {
			userOrdert = orderPayDao.getById(oid);
		} catch (Exception e) {

			response.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
			response.setErrorMessage(GrabOrderCodeMsg.GET_TAXI_ORDER_INFO_ERROR);
			response.setPromptMessage(GrabOrderCodeMsg.GET_TAXI_ORDER_INFO_ERROR_CLIENT);
			log.error("根据出租车订单Id获取订单信息时出现异常   类：" + this.getClass() + " geTaxiOrdert()", e);
			return userOrdert;
		}

		// 如果订单不存在，则给出相应的错误信息
		if (userOrdert == null) {
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(GrabOrderCodeMsg.ORDER_NOT_EXISTS);
			response.setPromptMessage(GrabOrderCodeMsg.ORDER_NOT_EXISTS);
		}

		return userOrdert;
	}

	/**
	 * 
	 * @Title: getOrderInfo 
	 * @Description: 根据出租车订单Id获取订单信息 
	 * @param oid 订单Id
	 * @author YHQ 
	 * @return UserTaxiOrdert    返回类型
	 * @version V2.3.0
	 * 
	 */
	@Transactional(readOnly = true)
	public Userorder getOrderInfo(String oid, ResponseEntity<ResTaxiQueryOrderResultDTO> response) {

		// 创建用于存储出租车订单的对象
		Userorder userOrder = null;

		try {
			userOrder = payUserOrderDao.getById(oid);
		} catch (Exception e) {

			response.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
			response.setErrorMessage(GrabOrderCodeMsg.GET_TAXI_ORDER_INFO_ERROR);
			response.setPromptMessage(GrabOrderCodeMsg.GET_TAXI_ORDER_INFO_ERROR_CLIENT);
			log.error("根据出租车订单Id获取订单信息时出现异常   类：" + this.getClass() + " geTaxiOrdert()", e);
			return userOrder;
		}

		// 如果订单不存在，则给出相应的错误信息
		if (userOrder == null) {
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(GrabOrderCodeMsg.ORDER_NOT_EXISTS);
			response.setPromptMessage(GrabOrderCodeMsg.ORDER_NOT_EXISTS);
		}

		return userOrder;
	}

	/**
	 * 
	 * @Title: getPayResultOperation 
	 * @Description: 获取支付结果操作
	 * @param userOrder 正式表数据
	 * @param taxiOrdert 出租车临时表数据
	 * @author YHQ 
	 * @since V2.3.0
	 * @return boolean    返回类型
	 * 
	 */
	public boolean getPayResultCondition(Userorder userOrder, Userordert userOrdert,
			ResponseEntity<ResTaxiQueryOrderResultDTO> response) {

		ResTaxiQueryOrderResultDTO taxiQueryOrderResultDTO = new ResTaxiQueryOrderResultDTO();

		// 正式表存在该订单，并且状态为已完成
		if (userOrder != null && userOrder.getOrderStatus() == OrderStatus.ORDER_STATUS_PAID) {

			// 1：支付成功 2：支付失败
			taxiQueryOrderResultDTO.setOrderStatus(1);

			response.setCode(HttpStatus.SC_OK);
			response.setErrorMessage(GetPayResultCodeMsg.GET_PAY_RESULT_SUCCESS);
			response.setPromptMessage(GetPayResultCodeMsg.GET_PAY_RESULT_SUCCESS);

			response.setResponseBody(taxiQueryOrderResultDTO);

			return true;
		}

		// 临时订单不为空，并且状态为待支付
		if (userOrdert != null && userOrdert.getOrderStatus() == OrderStatus.ORDER_STATUS_PAID) {

			// 1：支付成功 2：支付失败
			taxiQueryOrderResultDTO.setOrderStatus(1);
			
			response.setCode(HttpStatus.SC_OK);
			response.setErrorMessage(GetPayResultCodeMsg.GET_PAY_RESULT_SUCCESS);
			response.setPromptMessage(GetPayResultCodeMsg.GET_PAY_RESULT_SUCCESS);
			
			response.setResponseBody(taxiQueryOrderResultDTO);
			
			return true;
		}else if(userOrdert != null && userOrdert.getOrderStatus() == OrderStatus.ORDER_STATUS_PAY){
			
			if (wechatPayIsOk(userOrdert.getOid())) {
				
				userOrdert.setOrderStatus(OrderStatus.ORDER_STATUS_PAY);
				// 改变订单状态为已支付
				orderPayDao.update(userOrdert);
				
				// 1：支付成功 2：支付失败
				taxiQueryOrderResultDTO.setOrderStatus(1);
				
				response.setCode(HttpStatus.SC_OK);
				response.setErrorMessage(GetPayResultCodeMsg.GET_PAY_RESULT_SUCCESS);
				response.setPromptMessage(GetPayResultCodeMsg.GET_PAY_RESULT_SUCCESS);
				
				response.setResponseBody(taxiQueryOrderResultDTO);
				
				return true;
			}
			
		}

		// 1：支付成功 2：支付失败
		taxiQueryOrderResultDTO.setOrderStatus(2);

		response.setCode(HttpStatus.SC_FORBIDDEN);
		response.setErrorMessage(GetPayResultCodeMsg.GET_PAY_RESULT_ERROR);
		response.setPromptMessage(GetPayResultCodeMsg.GET_PAY_RESULT_ERROR);
		response.setResponseBody(taxiQueryOrderResultDTO);

		return false;
	}

	/**
	 * 
	 * @Title: getPayResultOperation 
	 * @Description: 获取支付结果操作
	 * @param userOrder 正式表数据
	 * @param taxiOrdert 出租车临时表数据
	 * @author YHQ 
	 * @since V2.3.0
	 * @return boolean    返回类型
	 * 
	 */
	public boolean getPayResultCondition(Userorder userOrder, UserTaxiOrdert taxiOrdert,
			ResponseEntity<ResTaxiQueryOrderResultDTO> response) {

		ResTaxiQueryOrderResultDTO taxiQueryOrderResultDTO = new ResTaxiQueryOrderResultDTO();

		// 正式表存在该订单，并且状态为已完成
		if (userOrder != null && userOrder.getOrderStatus() == TaxiOrderStatus.ORDER_STATUS_COMPLETE) {

			// 1：支付成功 2：支付失败
			taxiQueryOrderResultDTO.setOrderStatus(1);

			response.setCode(HttpStatus.SC_OK);
			response.setErrorMessage(GetPayResultCodeMsg.GET_PAY_RESULT_SUCCESS);
			response.setPromptMessage(GetPayResultCodeMsg.GET_PAY_RESULT_SUCCESS);

			response.setResponseBody(taxiQueryOrderResultDTO);

			return true;
		}

		// 临时订单不为空，并且状态为已完成
		if (taxiOrdert != null && taxiOrdert.getOrderStatus() == TaxiOrderStatus.ORDER_STATUS_COMPLETE
				&& taxiOrdert.getTransactionType() == TransactionTypeEnum.line.getIndex()) {

			// 1：支付成功 2：支付失败
			taxiQueryOrderResultDTO.setOrderStatus(1);

			response.setCode(HttpStatus.SC_OK);
			response.setErrorMessage(GetPayResultCodeMsg.GET_PAY_RESULT_SUCCESS);
			response.setPromptMessage(GetPayResultCodeMsg.GET_PAY_RESULT_SUCCESS);

			response.setResponseBody(taxiQueryOrderResultDTO);

			return true;
		}else if(taxiOrdert != null && taxiOrdert.getOrderStatus() == TaxiOrderStatus.ORDER_STATUS_PAID
				&& taxiOrdert.getTransactionType() == TransactionTypeEnum.line.getIndex()){  // 临时订单不为空，并且状态为待支付
			
			if (wechatPayIsOk(taxiOrdert.getTaxiOrdertId())) {

				taxiOrdert.setOrderStatus(OrderStatus.ORDER_STATUS_COMPLETE);
				
				// 改变订单状态为已支付
				taxiOrderPayDao.update(taxiOrdert);
				
				// 1：支付成功 2：支付失败
				taxiQueryOrderResultDTO.setOrderStatus(1);

				response.setCode(HttpStatus.SC_OK);
				response.setErrorMessage(GetPayResultCodeMsg.GET_PAY_RESULT_SUCCESS);
				response.setPromptMessage(GetPayResultCodeMsg.GET_PAY_RESULT_SUCCESS);

				response.setResponseBody(taxiQueryOrderResultDTO);

				return true;
			}
			
		}

		// 1：支付成功 2：支付失败
		taxiQueryOrderResultDTO.setOrderStatus(2);

		response.setCode(HttpStatus.SC_FORBIDDEN);
		response.setErrorMessage(GetPayResultCodeMsg.GET_PAY_RESULT_ERROR);
		response.setPromptMessage(GetPayResultCodeMsg.GET_PAY_RESULT_ERROR);
		response.setResponseBody(taxiQueryOrderResultDTO);

		return false;
	}

	/**
	 * 
	 * @Title: wechatPayIsOk 
	 * @Description: 请求微信是否扣款成功
	 * @param  
	 * @author YHQ 
	 * @since V2.3.0
	 * @return void    返回类型
	 * 
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean wechatPayIsOk(String oid) {

		// 调用api向微信发送请求，查看订单是否完成
		WechatPayApi api = new WechatPayApi();
		WechatPayOrderQueryResponse wechatResponse = api.orderQuery(createWechatPayQueryRequest(oid));

		// 如果微信返回的返回状态码和业务结果 都为“成功”
		if (wechatResponse != null && ("SUCCESS".equals(wechatResponse.getReturn_code())
				&& "SUCCESS".equals(wechatResponse.getResult_code()))) {

			// 如果微信服务器返回该订单已支付
			if ("SUCCESS".equals(wechatResponse.getTrade_state())) {
				return payNotifyService.paySuccessUpdateOrderStatus(oid, TransactionTypeEnum.line.getIndex(), false);
			}
		}

		return false;
	}

	/**
	 * @Title: createWechatPayQueryRequest
	 * @Description:创建微信支付查询支付结果请求bean
	 * @param 服务器本地的订单号
	 * @author fengshuonan
	 * @return WechatPayOrderQueryRequest
	 * @throws
	 */
	public static WechatPayOrderQueryRequest createWechatPayQueryRequest(String orderId) {

		if (ToolUtil.isBlank(orderId)) {
			return null;
		}

		WechatPayOrderQueryRequest request = new WechatPayOrderQueryRequest();
		request.setAppid("wx8b6d01f28792414a");// 叮叮搭车应用的appid
		request.setMch_id("1316301901");// 叮叮搭车应用商户号
		request.setNonce_str(ToolUtil.randomLenStr(20));// 生成20位随机码
		request.setOut_trade_no(orderId);

		// 生成签名
		String apiSec = "j5axbIfMSZjsiEGAScGMCUhp5kO2Oqaj";// API安全秘钥
		String stringSignTemp = ToolUtil.lexSortBean(request, WechatPayOrderQueryRequest.class) + "key=" + apiSec;
		String sign = MD5Util.md5Encrypt(stringSignTemp).toUpperCase();
		request.setSign(sign);

		return request;
	}

}
